<template>
  <div>
    <el-link @click="dialogFormVisible = true">{{title}}</el-link>
    <el-dialog
        title="收货地址"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :width="'500px'">
      <el-form :model="form">
        <el-form-item label="选择所在地" :label-width="formLabelWidth">
          <el-cascader size="large" :options="options" v-model="selectedOptions" @change="handleChange" />
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="收货人姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" style="width: 215px"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="form.telephone" autocomplete="off" style="width: 215px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAddress">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {CodeToText, regionData} from 'element-china-area-data'

export default {
  name: "addAddress",
  props: ['title'],
  data(){
    return {
      dialogFormVisible: false,
      options: regionData,
      selectedOptions: [],
      form: {
        city: '',
        address: '',
        name: '',
        telephone: ''
      },
      formLabelWidth:'120px',
    }
  },
  methods: {
    handleChange () {
      var loc = ''
      for (let i = 0; i < this.selectedOptions.length; i++) {
        loc += CodeToText[this.selectedOptions[i]]
      }
      this.form.city = loc
    },
    addAddress(){
      const userId = JSON.parse(sessionStorage.getItem("userInfo")).id
      this.$axios.post("/address", {
        userId: userId,
        name:this.form.name,
        telephone:this.form.telephone,
        city:this.form.city,
        address:this.form.address
      }).then(res => {
        this.$bus.$emit("addAddress1")
        this.$bus.$emit("addAddress2")
      })
      this.dialogFormVisible = false
      this.form.name = ''
      this.form.telephone = ''
      this.form.city = ''
      this.form.address = ''
    }
  },
}
</script>

<style scoped>

</style>